/**
 * 公共事件注册.
 * 1.键盘截取服务端日志
 * @author pengxiao
 * @since 2015-06-03
 */
define(["ecp.service", "jquery","ecp.utils","ecp.utils.des"],function(ecp,$,utils,desUtil) {
	var MemoryLog = {
			dlid: "ecpDownloadIframe",
			maxRow: 2000,
			prompt: "开启内存日志记录功能:\n设置截取最大行数为（此数值过大会影响系统性能 ）:",
		    beanId: "com.ygsoft.ecp.service.log.MemoryLogService",
		    service: "/grm/ecp/RemoteServiceServlet?callName=",
	    	setRowAndFileName:function () {
		    	$('.textBoxClass').css("display", "none");
		    	cnt = $('#textBoxDiv')[0].getElementsByTagName('input')[0].value;
		    	zipFileName = $('#textBoxDiv')[0].getElementsByTagName('input')[1].value;
		    	$.cookie("zipFileName",zipFileName);
		     	//var rs = bsportal.remoteService;
		     	if (cnt != null) {
                     ecp.RemoteService.doPostAsync("com.ygsoft.ecp.service.log.MemoryLogService","start",[null,cnt]);
		     		//doRemoteService(MemoryLog.service + "com.ygsoft.ecp.service.log.MemoryLogService.start(ip, rowCount)", {ip:null,rowCount:cnt}, "POST", false);
		     		//rs.doSynPost("com.ygsoft.ecp.service.log.MemoryLogService.start(ip, rowCount)",{ip:null,rowCount:cnt});
		     	}
			},  
			hidenextBox:function(){
				$('.textBoxClass').css('display', 'none');
			}
	};
	function formatError(respData){
		var ecpSErr;
		try{
		   //respData = respData.replace(/\r\n/g,"CRLF"); //回车换行将引起转换异常，替换掉
		    var p1,p2,p3,p4,
		    	mKey = '"msg": "',
		    	eKey = '"ecode": "',
		    	tKey = '"type": "',
		    	dKey = '"detail": "';
		    	
		    p1 = respData.indexOf(mKey);
		    p2 = respData.indexOf(eKey);
		    p3 = respData.indexOf(tKey);
		    p4 = respData.indexOf(dKey);
		    if(p1>-1 && p2>-1){
		    	var len = respData.length;
		    	ecpSErr={};
		    	ecpSErr.msg = respData.substring(p1+mKey.length,p2-3);
		    	ecpSErr.ecode = respData.substring(p2+eKey.length,p3-3);
		    	if( p4>-1 ){
		    		ecpSErr.type = respData.substring(p3+tKey.length, p4-3);
		    		ecpSErr.detail = respData.substring(p4+dKey.length, len-2);	
		    	}else{
		    		ecpSErr.type = respData.substring(p3+tKey.length, len-2);
		    	}
		    }else{
		    	ecpSErr = respData;
		    }
		    return ecpSErr;
		 }catch(e){
		    return respData;
		}
	}
	/**
	 * jQuery.Ajax调用服务.
	 * @param callName 远程调用请求
	 * @param data 请求参数
	 * @param methodType 请求类型
	 * @param async 是否异步
	 * @param callback 回调函数
	 */
	function doRemoteService(callName, data, methodType, async, callback, dataType) {
		var retObjet = null;
		var header = data._header;
		if (header) {
			delete data._header;
		}
		var dContext = data._reqContext;
		if (dContext) {
			delete data._reqContext;
		}
		var signification = desUtil.signData(callName, methodType || 'POST', data);
		var requestCallName =  callName;
		if(signification) {
			requestCallName = signification.RequestURI; 
		}
		$.ajax({
			url : requestCallName,
			data : data,
			type : methodType || 'POST',
			dataType: dataType || "json",
			contentType : "application/x-www-form-urlencoded; charset=UTF-8",
			async : async === undefined ? true : async,
			context : dContext || {},
			beforeSend : function(xhr){
				xhr.setRequestHeader("ECP_Version", "2.0");
				if (header) {
					for (var i=0, j=header.length; i < j; i++) {
						xhr.setRequestHeader(header[i].name, header[i].value);
					}
				}
				if(signification) {
					xhr.setRequestHeader("AZ", signification.AZ);
				}
				var cm = desUtil.getCmSign();
				if (cm) {
					xhr.setRequestHeader("CM", cm);
				}
	        },
			success : function(resdata, textStatus, jqXHR) {
				retObjet = resdata;
				if (callback) {
					callback(resdata, this, textStatus, jqXHR);
				}
			},
			error : function(jqXHR, textStatus, errorThrown) {
				var ecpSErr,ecpErr,respData;
				respData = jqXHR.responseText;
				ecpSErr = formatError(respData);
				if(typeof ecpSErr === "object") {
        			jqXHR.responseText = ecpSErr.msg; 
        		} else {
        			jqXHR.responseText = ecpSErr;
        		}
				if (ecpSErr.ecode === "SYS_ECP_NOT_LOGIN") {
					if (!$("#reloginModalDlg").is(":visible")) {
		    			//bsportal.tools.showReloginDlg();
		    		}
    				return;
    			}
				if (callback) {
					callback(null, null, textStatus, jqXHR, errorThrown);
				}
				//printException(ecpSErr);
			}
		});
		return retObjet;
	}		 
	var hostEl =  $(document).isFrame ? $(document).win.hostElement : undefined; 
	var helpIndex = "/grm/help/index.jsp";
	var isFrame = !(typeof hostEl === "undefined");
	/**
	 * 注册日志截取事件.
	 */
	function registLogEvent() {
		$(document).keydown(function(evt) {
			var kc = evt.keyCode;
			//帮助文档 ALT + Q 
			if(kc === 81 && evt.altKey==true){
				var t = (window.screen.availHeight-600)/2; //离顶部距离
				var l = (window.screen.availWidth-960)/2; //离左边距离 
				var	bodyHelpUrl;//=$body.attr("help");  //获取页面上面判断是否 手工填写body里面 help 路径，
				if(!isFrame){
					if(bodyHelpUrl == null){
							// 后面点对面JSON解析
								var cacheKey = "HelpIndexJsonCache";
								var confluenceTableCache; //= $.ecp.cacheManager.getGlobalCache(cacheKey);  //先从缓存里面获取数据
								if(confluenceTableCache == null){ //缓存为空，发起请求。	
									$.ajax({
										url : "/grm/ecp/HelpREFS/helpIndex.json",
										dataType : "json",
										type : "GET",
										success : function(resdata, textStatus, jqXHR) {
											resdata && openHelpPage(resdata,window.location.pathname,t,l);
										}
									});
								}else{ // 否则从缓存中获取。
									 openHelpPage(confluenceTableCache,window.location.pathname,t,l);
								}
					}else{
						 openHelpWinByUrl(helpIndex+"?"+bodyHelpUrl,t,l);
						 return;
					}
				}else{	
					var winHelp;
					winHelp = helpIndex;
					openHelpWinByUrl(winHelp,t,l);
				}
		    }
			if(kc === 13){
				if(evt.preventDefault){
					evt.preventDefault();
				} else {
					evt.returnValue = false;
				}
			}
			if (!evt.ctrlKey) {
				return;
			}
			var cnt, beanId = MemoryLog.beanId;
			setRowAndFileName = MemoryLog.setRowAndFileName ;
			hidenextBox = MemoryLog.hidenextBox;
	        if ((kc == 189 || kc == 109)) {
	        	// 开启记录内存日志，DEBUG ,ctrl alt - 
//	        	cnt = window.prompt(MemoryLog.prompt, MemoryLog.maxRow);
//	        	if (cnt != null) {
//	        		doRemoteService(MemoryLog.service + beanId+".start(ip, rowCount)", {ip:null,rowCount:cnt}, "POST", false);
//	        	}
	        	
        	 if($("#textBoxDiv").length<1){
	        	$("<div id='textBoxDiv' style='' class='textBoxClass'><table style='border-spacing:20px;border-collapse:collapse;'>开启内存日志记录功能:\n设置截取最大行数为(此数值过大会影响系统性能)</hr><tr><td>行数:</td><td><input name='row' value='2000'/></td></tr><tr><td>文件名:</td> <td><input name='zipFileName' value='单号.zip'/></td> </tr> <tr><td ><button onclick = 'setRowAndFileName();'>确定&nbsp&nbsp&nbsp</button></td><td style='padding:10px'><button  onclick = \"hidenextBox();\">关闭</button></td></tr></table></div>").appendTo('body');
	        	var style = document.createElement("style");
	        	style.type = "text/css";
	        	style.appendChild(document.createTextNode(".textBoxClass{ border: 3px solid orange; display: none; position: absolute;left: 0px; display: block;left:200px;width:520;hight:600px;top:100px; padding:5px; background-color: white;  z-index:100001;  -moz-opacity: 0.99;    opacity:1; filter: alpha(opacity=88); }  "));
	        	var head = document.getElementsByTagName("head")[0];
	        	head.appendChild(style);
        	 }
        	 document.getElementById("textBoxDiv").style.display='block';
	        } else if( (kc==187 ||kc==107)) {
	        	//关闭记录内存日志，下载压缩后的内存日志文件,ctrl alt +
	        	var zipLogName = "information.zip";
	        	if($.cookie("zipFileName")){
	        		zipLogName = $.cookie('zipFileName');
	        	}
                ecp.RemoteService.doPostAsync(beanId,"getOutputAndStop2",[null,decodeURI(zipLogName)],function(data){
                    if (data) {
                        var url, dlf, obj = data.data;
                        if (obj) {
                            url =  obj.url;
                        } else {
                            url = data.url;
                        }
                        if (url) {
                            url = "/grm/ecp/" + url;
                            if (isNaN(utils.getIEVersion())) {
                                var doc = document;
                                dlf = doc.getElementById(MemoryLog.dlid);
                                if (dlf == null) {
                                    dlf = doc.createElement("iframe");
                                    dlf.id = MemoryLog.dlid;
                                    dlf.style.display="none";
                                    doc.body.appendChild(dlf);
                                }
                                dlf.src = url;
                            } else {
                                window.open(url);
                            }
                        }
                    }
                });
	        } else if( kc==220) {
	        	//获取内存日志快照，同时关闭记录内存日志,在新的页签中显示， ctrl alt \
	        	var log =doRemoteService(MemoryLog.service + beanId+".getMemoryLog(ip)",{ip:null},null,false,null,"text");
	        	var win = window.open('about:blank');
	        	win.document.write('<pre>'+log+'</pre>');
	        } else if (kc == 191) {
	        	var nodeName = doRemoteService(MemoryLog.service + beanId+".getServerName()",{},null,false,null,"text");
	        	alert("当前访问节点：" + nodeName);
	        }
		});
	}
	/**
	* 帮助文档显示
	* <p>
	*  工具堆栈信息 先进后出的原则,循环匹配caCheData缓存数据，找url出帮助文档节点，然后打开，没有找到情况下，打开默认文档主页
	* </p>
	* @param {Object} cacheData 循环缓存数据  格式[{ url:"功能URL",helpModule:"路径模块", helpNode:"11043799" }]
	* @param {String} winUrl 堆栈信息
	* @param {String} economyPath 打开帮助文档路径
	* @param {String} t 离顶部距离
	* @param {String} l 离左边距离  
	*/
	function openHelpPage(cacheData,winUrl,t,l){
		var helpUrl,found=false;
		var sz =cacheData.length;
		for(var j= winUrl.length;j>0;j--){
				var _url =  winUrl;
				if(_url && _url.startsWith("http")!==-1){
					_url =_url.substring(_url.indexOf("/grm"));
				}
				if(_url && _url.indexOf("?")!==-1){
					_url =_url.substring(0,_url.indexOf("?"));
				}
				for(var i=0; i< sz ;i++){
					var nd = cacheData[i];
					if(nd.url != null && _url == nd.url.trim()){
						helpUrl= helpIndex+"?topic=/"+nd.helpModule+"/docs/"+nd.helpNode.trim()+".html";
						found = true;
						break ;
					}
				}
				if(found){break;}
		}
		if(!found){
			helpUrl=helpIndex;
		}
		openHelpWinByUrl(helpUrl,t,l);
	}
	function openHelpWinByUrl(helpUrl,top,left){
		var opt = "height=600, width=960,top="+top+",left="+left+",toolbar=yes,resizable=yes,location=yes,status=yes";
		window.open(helpUrl,'newWindow', opt);
	}
	registLogEvent();
});